package com.lemo.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class QuestionDemo {

	public static void main(String[] args) {

		Demo demo = new Demo();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 1; i <= 20; i++) {
					try {
						demo.loopA(i);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "A").start();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 1; i <= 20; i++) {
					try {
						demo.loopB(i);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "B").start();
		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 1; i <= 20; i++) {
					try {
						demo.loopC(i);
						System.out.println("----------------");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}, "C").start();
	}

}

class Demo {

	private int num = 1;

	private Lock lock = new ReentrantLock();

	private Condition condition1 = lock.newCondition();
	private Condition condition2 = lock.newCondition();
	private Condition condition3 = lock.newCondition();

	public void loopA(int total) throws InterruptedException {
		lock.lock();

		try {
			if (num != 1) {
				condition1.await();
			}

			for (int i = 1; i <= 1; i++) {
				System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + total);
			}

			num = 2;
			condition2.signal();

		} finally {
			lock.unlock();
		}
	}

	public void loopB(int total) throws InterruptedException {

		lock.lock();
		try {
			if (num != 2) {
				condition2.await();
			}

			for (int i = 1; i <= 1; i++) {
				System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + total);
			}

			num = 3;
			condition3.signal();

		} finally {
			lock.unlock();
		}
	}

	public void loopC(int total) throws InterruptedException {
		lock.lock();

		try {
			if (num != 3) {
				condition3.await();
			}

			for (int i = 1; i <= 1; i++) {
				System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + total);
			}

			num = 1;
			condition1.signal();

		} finally {
			lock.unlock();
		}
	}

}